<?php

define('DIR_BASE', implode(DS, array(APP::$ROOT, 'public', 'img', 'products')));

class AdminProductsController extends AdminController {

    public function index($categoryId=null) {

        $conditions = array();

        if ($categoryId>0) {
            $childrenIds = CategoryModel::childrenIds($categoryId);

            $conditions['category_id'] = array_merge($childrenIds, array($categoryId));
            $this->set('category_id', $categoryId);
        }

        $data = ProductModel::build()
                ->join('Category')
                ->where($conditions)
                ->order('Product.name')
                ->query();
        
        $this->set('categories', CategoryModel::tree());
        $this->set('data', $data);

        if ($this->isAjax()) {
            $this->render('products', false);
        }
    }

    public function create($categoryId) {
        $this->set('categories', CategoryModel::tree());

        if ($this->isAjax()) {
            $this->render('form', false);
        }
    }

    public function edit($id) {
        $this->set('categories', CategoryModel::tree());
        $this->set('product', ProductModel::get($id));

        if ($this->isAjax()) {
            $this->render('form', false);
        }
    }

    public function save() {
        $data = $this->POST('data');
        $data['image'] = preg_replace('/^\/?img\/products(\/\d*\/)?/i', '', $data['image']);

        if (! empty($data)) {
            $id         = (int)$data['id'];
            $categoryId = (int)$data['category_id'];

            $oldData = $id>0 ? ProductModel::get($id) : false;

            $file = $this->getUploadImages('data_image_file', $data, $oldData);

            // validate image file, if needed
            if ($file->error) {
                return $this->saveFailed($file->error, $data);
            }

            $data['image'] = $file->name();
            if ($id) {
                $saved = ProductModel::update($data, array('id' => $data['id']));
            } else {
                unset($data['id']);
                $saved = ProductModel::insert($data);
                $id = ProductModel::lastInsertId();
            }

            if ($saved) {
                $file->process(DIR_BASE . DS . $categoryId);

                $this->flash('Proizvod je sačuvan', 'ok');
                $hash = "#!/admin_products/edit/{$id}/{$categoryId}";
            } else {
                $this->flash('Proizvod nije sačuvan');
            }
        }
        
        $this->redirect("/admin_products/{$hash}");
    }

    public function remove($id) {
        $hash = '';
        if (ProductModel::delete(array('id' => $id))) {
            $this->flash('Proizvod je obrisan.', 'ok');
        } else {
            $hash = "#!/admin_products/edit/{$id}";
            $this->flash('Proizvod nije obrisana.');
        }

        $this->redirect("/admin_products/{$hash}");
    }

    private function saveFailed($message, $data) {
        $this->flash($message);
        $this->set('categories', CategoryModel::tree());
        $this->set('product', (object)$data);
        $this->render('form');
    }

}